package cn.xy.base.server.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.spec.IvParameterSpec;
import java.security.spec.AlgorithmParameterSpec;

@Slf4j
@Service
public class AesService {

    /**
     * 定义 aes 加密的key
     */
    @Value("${aesKey.mysqlKey}")
    private String aesKey;

    /**
     * 偏移量
     */
    private static final int OFFSET = 16;

    public String encrypt(String content) {
        return encrypt(content, this.aesKey);
    }

    public String decrypt(String content) {
        return decrypt(content, this.aesKey);
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return 加密的内容
     */
    public String encrypt(String content, String key) {
        try {
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes());
            aes.setIv(new IvParameterSpec(key.getBytes(), 0, OFFSET));
            return aes.encryptBase64(content);
        } catch (Exception e) {
            log.error("aes 加密失败: {}", e.getMessage());
        }
        return null;
    }

    /**
     * AES（256）解密
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return 解密之后
     */
    public String decrypt(String content, String key) {
        try {
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes());
            aes.setIv(new IvParameterSpec(key.getBytes(), 0, OFFSET));
            return aes.decryptStr(content);
        } catch (Exception e) {
            log.error("aes 解密失败: {}", e.getMessage());
        }
        return null;
    }

}
